# -*- coding: utf-8 -*-
'''
@author: olivia.dou
Created on: 2022/4/20 16:41
desc:
'''
import time, logging
import base.globalvars as glo
from util.date_util import timestamp_to_str
from util.db_util import execute_query


def get_std_qc_element_status(file_id, element_id, start_time, timeout=60):

    start_time_str = timestamp_to_str(start_time)
    sql = "SELECT status FROM t_das_std_qc_element_result WHERE file_id=%s AND element_id=%s AND upt>='%s'"%(file_id, element_id, start_time_str)

    res = execute_query(sql)
    while res==[] and time.time()-int(glo.get_value("time_difference")) - start_time < timeout:
        res = execute_query(sql)
        time.sleep(3)

    return res


def get_std_qc_element_result(file_elements, start_time, timeout=60):
    """

    :param file_elements:
    :param start_time:
    :param timeout:

    :return:
    """
    file_elements_str = ','.join(str(item) for item in file_elements)
    start_time_str = timestamp_to_str(start_time)
    sql = "SELECT file_id, element_id, status FROM t_das_std_qc_element_result WHERE (file_id, element_id) in (%s) AND upt>='%s'"\
          %(file_elements_str, start_time_str)

    res = execute_query(sql)
    while len(res)<len(file_elements) and time.time()-int(glo.get_value("time_difference",defValue=0)) - start_time < timeout:
        res = execute_query(sql)
        time.sleep(3)

    return res

def set_std_qc_element_result(file_id, model_id, element_id, status, **kwargs):
    """
    设置标准化质检的状态
    status: -1（删除），0（质检正确），1（质检错误），2（质检不适用）
    """
    if status == -1:
        sql = f"DELETE FROM t_das_std_qc_element_result WHERE element_id='{element_id}' AND file_id='{file_id}' AND qcgroup='{kwargs['qc_group']}'"
    else:
        # 查询数据是否存在，再做插入/更新操作
        select_sql = f"select status from t_das_std_qc_element_result where element_id='{element_id}' AND file_id='{file_id}' AND qcgroup='{kwargs['qc_group']}'"
        try:
            res = execute_query(select_sql)
        except Exception as e:
            logging.error(e)
            logging.error("sql: %s" % select_sql)
            raise e

        if len(res) == 0:
            sql = f"INSERT INTO t_das_std_qc_element_result VALUES (null, 'test_batch', {file_id}, {kwargs['qc_group']}, {model_id}, {element_id}, '', {status}, 'test', 'automation', 'Automation', null,'Automation',null)"
        else:
            sql = f"UPDATE t_das_std_qc_element_result SET status={status} where element_id='{element_id}' AND file_id='{file_id}' AND qcgroup='{kwargs['qc_group']}'"

    try:
        execute_query(sql)
        execute_query("commit;")
    except Exception as e:
        logging.error(e)

def set_outer_qc_result(file_id, model_id, element_id, status):
    """
    设置外部质检的状态
    status: -1（删除），0（质检正确），1（质检错误）
    """
    if status == -1:
        sql = f"DELETE FROM t_das_outer_qc_result WHERE element_id='{element_id}' AND file_id='{file_id}'"
    else:
        # 查询数据是否存在，再做插入/更新操作
        select_sql = f"select status from t_das_outer_qc_result where element_id='{element_id}' AND file_id='{file_id}'"
        try:
            res = execute_query(select_sql)
        except Exception as e:
            logging.error(e)
            logging.error("sql: %s" % select_sql)
            raise e

        if len(res) == 0:
            sql = f"INSERT INTO t_das_outer_qc_result VALUES (null, 'test_batch', {file_id}, {model_id}, {element_id}, '', '', {status}, 'test', null, 'Automation', null,'Automation',null,null)"
        else:
            sql = f"UPDATE t_das_outer_qc_result SET status={status} where element_id='{element_id}' AND file_id='{file_id}'"

        try:
            execute_query(sql)
            execute_query("commit;")
        except Exception as e:
            logging.error(e)